<?php

$di       = \application\units\Di::getInstance();
$account  = $di->request->params('account');
$password = $di->request->params('password');

if (!$account) throw new LogicException('账号不能为空', 10000);
if (!$password) throw new LogicException('密码不能为空', 10000);

$admin = $di->db->find('select * from admin where email=:email or username=:username', [
    'email'    => $account,
    'username' => $account,
]);

if (!$admin) throw new LogicException('账号或密码无效', 10001);

if ($admin['loginfailure'] >= 10 && strtotime($admin['update_time']) >= time() - 300) throw new LogicException(sprintf('密码输入错误次数超过%s次，请5分钟后再尝试！', $admin['loginfailure']), 10002);

if ($admin['password'] !== md5(md5($password) . $admin['salt'])) {
    $admin['update_time']  = date('Y-m-d H:i:s');
    $admin['loginfailure'] += 1;
    // 密码不正确更新登录失败次数
    $stmt = $di->db->execute('update admin set loginfailure=:loginfailure,update_time=:update_time where id=:id', [
        'update_time'  => $admin['update_time'],
        'loginfailure' => $admin['loginfailure'],
        'id'           => $admin['id'],
    ]);
    
    if ($stmt->rowCount() <= 0) throw new PDOException('登录失败', 10001);
    $loginfailure = 10 - $admin['loginfailure'];
    
    if ($loginfailure <= 0) throw new LogicException('账号或密码无效，错误次数超过10次，请5分钟后再尝试！', 10001);
    if ($loginfailure <= 3) throw new LogicException(sprintf('账号或密码无效，错误次数剩余%s次！', $loginfailure), 10001);
    
    throw new LogicException('账号或密码无效', 10001);
}

if ($admin['status'] == 0) throw new LogicException('账号已禁用', 10002);

$admin['login_time']        = date('Y-m-d H:i:s');
$admin['update_time']       = date('Y-m-d H:i:s');
$admin['loginfailure']      = 0;
$admin['token']             = md5(random_bytes(32));
$admin['token_expiry_time'] = date('Y-m-d H:i:s', strtotime('+7 day'));

// 登录成功后更新信息
$stmt = $di->db->execute('update admin set login_time=:login_time,token=:token,token_expiry_time=:token_expiry_time,update_time=:update_time,loginfailure=:loginfailure where id=:id', [
    'login_time'        => $admin['login_time'],
    'update_time'       => $admin['update_time'],
    'token'             => $admin['token'],
    'token_expiry_time' => $admin['token_expiry_time'],
    'loginfailure'      => $admin['loginfailure'],
    'id'                => $admin['id'],
]);

if ($stmt->rowCount() <= 0) throw new PDOException('登录失败', 10001);

$admin['token'] = sprintf('%s-%s', $admin['id'], $admin['token']);

setcookie('token', $admin['token'], 0, '/', '', false, false);

$di->auth->log([
    'admin_id'    => $admin['id'],
    'username'    => $admin['username'],
    'url'         => $di->request->server('HTTP_REFERER'),
    'title'       => $di->request->params('method'),
    'content'     => json_encode($di->request->params(), JSON_UNESCAPED_UNICODE),
    'ip'          => $di->request->ip(),
    'useragent'   => $di->request->server('HTTP_USER_AGENT'),
    'create_time' => date('Y-m-d H:i:s'),
]);

return [
    'admin' => [
        'token' => $admin['token'],
    ],
];